﻿using DevComponents.DotNetBar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;

namespace UniRlv.UI.CodeLook
{
    public partial class FrmMain : DevComponents.DotNetBar.OfficeForm
    {
        List<Dictionary<string, object>> liWholeCodes = new List<Dictionary<string, object>>();
        DataTable dtCurCodes;
        int nTotalPages;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            RefreshSrvStrings(ConfigurationHelper.AppGetString("ips"));

            if (lstSrvIPs.Items.Count>0)
            {
                lstSrvIPs.SelectedIndex = 0;
            }

            lstCdt.SelectedIndex = 0;
            lstCdt2.SelectedIndex = 0;

            panelTxt.Visible = true;
            panelDate.Visible = false;
            panelTxt2.Visible = true;
            panelDate2.Visible = false;

            dtpFrom.Value = DateTime.Now;
            dtpTo.Value = DateTime.Now;
            dtpFrom2.Value = DateTime.Now;
            dtpTo2.Value = DateTime.Now;

            UIHelper.InitDataGridView(dgvTasks);
            UIHelper.InitDataGridView(dgvCodes);

            string ver = string.Format(" V{0}.{1}.{2}",
                Assembly.GetExecutingAssembly().GetName().Version.Major,
                Assembly.GetExecutingAssembly().GetName().Version.Minor,
                Assembly.GetExecutingAssembly().GetName().Version.Build);

            this.Text += ver;
        }

        private void btnSrvEdit_Click(object sender, EventArgs e)
        {
            FrmSrvSetting frm = new FrmSrvSetting();

            frm.Tag = ConfigurationHelper.AppGetString("ips");
            if (frm.ShowDialog() == DialogResult.OK)
            {
                RefreshSrvStrings(frm.Tag.ToString());

                ConfigurationHelper.AppSet("ips", frm.Tag.ToString());

                if (lstSrvIPs.Items.Count>0)
                {
                    lstSrvIPs.SelectedIndex = lstSrvIPs.Items.Count - 1;
                }
                
            }
        }

        void RefreshSrvStrings(string ips)
        {
            lstSrvIPs.Items.Clear();

            if (!string.IsNullOrEmpty(ips))
            {
                string[] items = ips.Split(new char[] { '|' });

                lstSrvIPs.Items.AddRange(items);

            }
        }

        private void lstCdt_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstCdt.SelectedIndex == 4)
            {
                panelDate.Visible = true;
                panelTxt.Visible = false;
            }
            else
            {
                panelDate.Visible = false;
                panelTxt.Visible = true;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string whereString = " state>3 and ";
            string msg = string.Empty;

            if (string.IsNullOrEmpty(lstSrvIPs.Text))
            {
                MessageBoxEx.Show("请先配置服务端IP信息");
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            try
            {
                string ip = lstSrvIPs.Text.Split(new char[] { ',' })[1];
                string connString = ConfigurationHelper.AppGetString("connStrings");
                SqlHelper.connStr = string.Format(connString, ip);

                if (chkArchieveTask.Checked)
                {
                    SqlHelper.connStr = SqlHelper.connStr.Replace("unirlv", "UniRlv_archive");
                    SqlHelper.connStr = SqlHelper.connStr.Replace("Unirlv", "UniRlv_archive");
                }

                dgvTasks.DataSource = null;
                lbQueryTip.Text = string.Format("查询到0条记录，一级码扫描数量累计0个");

                switch (lstCdt.SelectedIndex)
                {
                    case 0://品名
                        whereString += string.Format("spm like '%{0}%'", txtTxt.Text);
                        break;
                    case 1://通用名
                        whereString += string.Format("tym LIKE '%{0}%'", txtTxt.Text);
                        break;
                    case 2://批次号
                        whereString += string.Format("batch LIKE '%{0}%'", txtTxt.Text);
                        break;
                    case 3://审核人
                        whereString += string.Format("verifyer LIKE '%{0}%'", txtTxt.Text);
                        break;
                    case 4://生产日期
                        whereString += string.Format(" produceDate >= '{0}' and produceDate <= '{1}'", dtpFrom.Value.ToString("yyyy-MM-dd 00:00:00"), dtpTo.Value.ToString("yyyy-MM-dd 23:59:59"));
                        break;
                    case 5://条码
                        CodeInfo code = DALOpr.QuerySingle<CodeInfo>("select * from codeinfo where code='" + txtTxt.Text + "'", ref msg);

                        if (code == null)
                        {
                            MessageBoxEx.Show("查询出错：" + msg);
                            return;
                        }
                        else
                        {
                            whereString += string.Format("id = {0}", code.taskID);
                        }
                        break;
                    case 6://任务号
                        whereString += string.Format("id= {0}", txtTxt.Text);
                        break;
                    default:
                        break;
                }


                List<ProductionTask> li = DALOpr.Query<ProductionTask>(whereString, ref msg);

                if (string.IsNullOrEmpty(msg))
                {

                    dgvTasks.DataSource = li;

                    lbQueryTip.Text = string.Format("查询到{0}条记录，一级码扫描数量累计{1}个", li.Count, li.Sum(s1 => s1.scanQuantity));
                }
                else
                {
                    MessageBoxEx.Show(msg);
                }
            }
            catch (Exception exp)
            {
                MessageBoxEx.Show("查询出现异常：" + exp.Message);
            }

            this.Cursor = Cursors.Default;
        }

        private void lstCdt2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstCdt2.SelectedIndex == 2 || lstCdt2.SelectedIndex == 3)
            {
                panelDate2.Visible = true;
                panelTxt2.Visible = false;
            }
            else
            {
                panelDate2.Visible = false;
                panelTxt2.Visible = true;
            }

            lstFilter.Enabled = lstCdt2.SelectedIndex == 4;
            lstFilter.SelectedIndex = 0;
        }

        private void btnQuery2_Click(object sender, EventArgs e)
        {
            string whereString = " ";
            string msg = string.Empty;
            CodeInfo code = null;

            if (string.IsNullOrEmpty(lstSrvIPs.Text))
            {
                MessageBoxEx.Show("请先配置服务端IP信息");
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            try
            {
                liWholeCodes.Clear();

                if (dtCurCodes != null)
                {
                    dtCurCodes.Clear();
                }

                dgvCodes.DataSource = null;
                nTotalPages = 0;
                lbAllTip.Text = string.Format("共0条记录，每页50条，共0页");

                string ip = lstSrvIPs.Text.Split(new char[] { ',' })[1];

                
                if (chkArchieveData.Checked)
                {
                    SqlHelper.connStr = string.Format(@"server={0}\SQLEXPRESS08;database=UniRlv_archive;uid=sa;pwd=connortao", ip);
                }
                else
                {
                    SqlHelper.connStr = string.Format(@"server={0}\SQLEXPRESS08;database=unirlv;uid=sa;pwd=connortao", ip);
                }
                

                switch (lstCdt2.SelectedIndex)
                {
                    case 0://任务号
                        whereString += string.Format("ID = {0}", txtTxt2.Text);
                        break;
                    case 1://批次号
                        whereString += string.Format("batch LIKE '%{0}%'", txtTxt2.Text);
                        break;
                    case 2://操作日期
                        whereString += string.Format(" operateDate >= '{0}' and operateDate <= '{1}'", dtpFrom2.Value.ToString("yyyy-MM-dd 00:00:00"), dtpTo2.Value.ToString("yyyy-MM-dd 23:59:59"));
                        break;
                    case 3://生产日期
                        whereString += string.Format(" produceDate >= '{0}' and produceDate <= '{1}'", dtpFrom2.Value.ToString("yyyy-MM-dd 00:00:00"), dtpTo2.Value.ToString("yyyy-MM-dd 23:59:59"));
                        break;
                    case 4://条码
                        code = DALOpr.QuerySingle<CodeInfo>("select * from codeinfo where code='" + txtTxt2.Text + "'", ref msg);

                        if (code == null)
                        {
                            MessageBoxEx.Show("查询出错：" + msg);
                            this.Cursor = Cursors.Default;
                            return;
                        }
                        else
                        {
                            whereString += string.Format("ID = {0}", code.taskID);
                        }
                        break;
                    default:
                        break;
                }


                List<ProductionTask> li = DALOpr.Query<ProductionTask>(whereString, ref msg);
                

                if (string.IsNullOrEmpty(msg))
                {
                    if (li.Count > 0)
                    {
                        if (lstCdt2.SelectedIndex == 4 && lstFilter.SelectedIndex == 0)
                        {//条码自身
                            Dictionary<string, object> di = EntityHelper.GetDicData(code);
                            di.Add("batch", li[0].batch);
                            di.Add("spm", li[0].spm);
                            di.Add("pzwh", li[0].pzwh);
                            liWholeCodes.Add(di);

                            nTotalPages = 1;
                            lbAllTip.Text = string.Format("共1条记录，每页50条，共1页");

                            GotoPage(1);
                            this.Cursor = Cursors.Default;
                            return;
                        }

                        List<CodeInfo> codes = null;
                        List<Dictionary<string, object>> dict;
                        foreach (var item in li)
                        {
                            whereString = string.Format("(codestate={0} or codestate={1} or codestate={2}) and taskID={3}", (int)code_state.CS_SCANED, (int)code_state.CS_PRINTED, (int)code_state.CS_IMP, item.ID);
                            codes = DALOpr.Query<CodeInfo>(whereString, ref msg);
                            if (codes!=null && codes.Count>0)
                            {
                                dict = EntityHelper.GetDicDatas(codes);
                                for (int i = 0; i < dict.Count; i++)
                                {
                                    dict[i].Add("batch", item.batch);
                                    dict[i].Add("spm", item.spm);
                                    dict[i].Add("pzwh", item.pzwh);
                                }
                                liWholeCodes.AddRange(dict);
                            }

                            if (lstCdt2.SelectedIndex == 4)
                            {
                                CodePrcUtility.CurTask = item;
                                CodePrcUtility.arrCode1 = codes.FindAll(s => s.stationNumber == 1).OrderBy(s => s.serialNumber).ToList();
                                CodePrcUtility.arrCode2 = codes.FindAll(s => s.stationNumber == 2).OrderBy(s => s.serialNumber).ToList();
                                CodePrcUtility.arrCode3 = codes.FindAll(s => s.stationNumber == 3).OrderBy(s => s.serialNumber).ToList();
                                CodePrcUtility.arrCode4 = codes.FindAll(s => s.stationNumber == 4).OrderBy(s => s.serialNumber).ToList();
                            }
                        }

                        if (lstCdt2.SelectedIndex == 4)
                        {//条码内容查询，进一步查看过滤条件
                            CodeInfo parent;
                            List<CodeInfo> tmpCodes = null;

                            liWholeCodes.Clear();
                            int idx = CodePrcUtility.FindCodePos(code);

                            switch (lstFilter.SelectedIndex)
                            {
                                case 1://相邻条码
                                    tmpCodes = CodePrcUtility.FindArrayByPos1(code.stationNumber, idx, 3);
                                    break;
                                case 2://父码
                                    parent = CodePrcUtility.GetParent(code, ref msg);

                                    if (parent == null)
                                    {
                                        MessageBoxEx.Show("提示", msg);
                                    }
                                    else
                                    {
                                        tmpCodes = new List<CodeInfo>();
                                        tmpCodes.Add(parent);
                                    }
                                    break;
                                case 3://同级+父码
                                    parent = CodePrcUtility.GetParent(code, ref msg);
                                    if (parent == null)
                                    {
                                        MessageBoxEx.Show("提示", msg);
                                    }
                                    else
                                    {
                                        tmpCodes = CodePrcUtility.GetLevelSonPackageCodes(parent, ref msg);

                                        if (tmpCodes == null)
                                        {
                                            MessageBoxEx.Show("提示", msg);
                                        }
                                        else
                                        {
                                            tmpCodes.Add(parent);
                                        }
                                    }
                                    break;
                                case 4://自身+子码
                                    tmpCodes = CodePrcUtility.GetLevelSonPackageCodes(code, ref msg);

                                    if (tmpCodes == null)
                                    {
                                        MessageBoxEx.Show("提示", msg);
                                    }
                                    else
                                    {
                                        tmpCodes.Add(code);
                                    }
                                    break;
                                case 5://整包装
                                    tmpCodes = CodePrcUtility.GetWholePackageCodes(code, ref msg);

                                    if (tmpCodes == null)
                                    {
                                        MessageBoxEx.Show("提示", "查询出错：" + msg);
                                    }
                                    break;
                                default:
                                    this.Cursor = Cursors.Default;
                                    return;
                            }

                            dict = EntityHelper.GetDicDatas(tmpCodes);
                            for (int i = 0; i < dict.Count; i++)
                            {
                                dict[i].Add("batch", CodePrcUtility.CurTask.batch);
                                dict[i].Add("spm", CodePrcUtility.CurTask.spm);
                                dict[i].Add("pzwh", CodePrcUtility.CurTask.pzwh);
                            }

                            liWholeCodes.AddRange(dict);
                        }

                        nTotalPages = (liWholeCodes.Count + 49) / 50;
                        lbAllTip.Text = string.Format("共{0}条记录，每页50条，共{1}页", liWholeCodes.Count, nTotalPages);


                        if (liWholeCodes.Count > 0)
                        {
                            GotoPage(1);
                        }
                        else
                        {
                            txtPage.Text = "0";
                        }
                    }
                    else
                    {
                        MessageBoxEx.Show("无法查询到码所在的任务信息");

                        if (lstCdt2.SelectedIndex == 4 && lstFilter.SelectedIndex == 0)
                        {//条码自身
                            Dictionary<string, object> di = EntityHelper.GetDicData(code);
                            liWholeCodes.Add(di);

                            nTotalPages = 1;
                            lbAllTip.Text = string.Format("共1条记录，每页50条，共1页");

                            GotoPage(1);

                        }
                        else
                        {
                            dgvCodes.DataSource = null;
                            nTotalPages = 0;
                            lbAllTip.Text = string.Format("共0条记录，每页50条，共0页", liWholeCodes.Count);
                        }

                        

                    }
                }
                else
                {
                    MessageBoxEx.Show(msg);
                }
            }
            catch (Exception exp)
            {
                MessageBoxEx.Show("查询出现异常：" + exp.Message);
            }

            this.Cursor = Cursors.Default;
        }


        private void btnFirst_Click(object sender, EventArgs e)
        {
            GotoPage(1);
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            try
            {
                int np = Convert.ToInt32(txtPage.Text);
                GotoPage(np-1);
            }
            catch (Exception)
            {

            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                int np = Convert.ToInt32(txtPage.Text);
                GotoPage(np + 1);
            }
            catch (Exception)
            {

            }
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            GotoPage(nTotalPages);
        }

        private void txtPage_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                GotoPage(Convert.ToInt32(txtPage.Text));
            }
            catch (Exception)
            {

            }
            
        }

        void GotoPage(int page)
        {
            int gp = page;

            if (page<1)
            {
                gp = 1;
            }

            if (page>nTotalPages)
            {
                gp = nTotalPages;
            }

            dgvCodes.DataSource = null;
            dgvCodes.Tag = (gp - 1) * 50;
            dtCurCodes = liWholeCodes.Skip(50*(gp-1)).Take(50).ToList().ToDataTable();
            dtCurCodes.CaseSensitive = false;
            dtCurCodes.TableName = "CodeInfo";
            dgvCodes.DataSource = dtCurCodes;
            txtPage.Text = gp.ToString();
        }


        private void dgvCodes_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvCodes.CurrentRow != null)
            {
                DataRow dr = (dgvCodes.CurrentRow.DataBoundItem as DataRowView).Row;

                if (lstCdt2.SelectedIndex == 4)
                {
                    txtTxt2.Text = dr["code"].ToString();
                }
            }
        }
    }
}
